import { Form } from 'antd-mini/es/Form/form';
import { UserInfoType } from '../../types/index';
import api from '../../utils/api';
import util from '../../utils/common';

Page({
  data: {
    isShow: false
  },
  form: new Form(),
  onLoad() {
    this.form = new Form({
      rules: {
        email: [
          {
            required: true,
            message: '请输入电子邮箱地址'
          },
          (form) => ({
            async validator(_, value) {
              const emailReg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
              if (!value || emailReg.test(form.getFieldValue('email'))) {
                return;
              }
              throw new Error('请输入正确的电子邮箱');
            },
          })
        ]
      },
    });
  },
  handleRef(ref) {
    this.form.addItem(ref);
  },
  onIconChange() {
    this.setData({
      isShow: !this.data.isShow
    })
  },
  async submit() {
    const values = await this.form.submit();
    const data = {
      ...values,
      roles: 'author',
    }
    const res: UserInfoType = await api.getAdminToken();
    if (res?.token) {
      my.setStorageSync({key: 'token', data: res.token});
      api.register(data).then(result => {
        if (result) {
          my.removeStorageSync({key: 'token'});
          util.showToast('注册成功', 'success', () => {
            my.navigateTo({
              url: `/pages/login/login`,
            })
          })
        }
      })
    }
  },
});
